import { Message } from 'element-ui';
import router from '@/router';
import { notLoginErrCodes } from '@/constants';
import {
  insertResponseInterceptors,
  get,
  post,
  setOpts,
  setGlobalParamsMaker,
} from '@/utils/request';

//未登录 errcode
const VUE_APP_API_BASE_URL = process.env.VUE_APP_API_BASE_URL || '';

function goLogin() {
  const currentPath = router.currentRoute.fullPath;
  !currentPath.match(/\/login/) &&
    router.replace({
      name: 'login',
      params: {
        refererRoute: router.currentRoute,
      },
      query: {
        currentPath,
      },
    });
}

const interceptor = function(res = {}) {
  let { errcode, errmsg, message, response } = res;
  if (response) {
    const { data } = response;
    Message.error(data.error);
    return Promise.reject({ code: data.status, message: data.error });
  }
  if (+errcode === 0) {
    return res;
  } else {
    if (notLoginErrCodes.includes(+errcode)) {
      goLogin();
    } else if (errmsg) {
      Message.warning(errmsg);
    } else if (message) {
      // 网络错误
      Message.warning(message);
    }
    return Promise.reject(res);
  }
};
//设置reponse拦截器
insertResponseInterceptors(interceptor);
//设置axios基础配置
setOpts({
  baseURL: VUE_APP_API_BASE_URL,
});
//设置全局请求参数
setGlobalParamsMaker(function() {
  return {};
});
export { get, post };
